<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/5/10
 * Time: 9:55
 */

namespace Home\Controller;

use Home\Exception\HomeException;
use Home\Request\Act\GetActRequest;
use Home\Request\Apply\ActApplyTimeRequest;
use Home\Request\Apply\AddNumRequest;
use Home\Request\Apply\CheckApplyRequest;
use Home\Request\Apply\FindApplyRequest;
use Home\Request\Apply\SelectApplyRequest;
use Home\Request\Apply\SubmitMsgRequest;
use Home\Request\Document\GetEventRequest;
use Home\Request\record\AddRecordRequest;
use Home\Request\User\CheckDayNumRequest;
use Home\Request\User_weixin\GetWeixinIdRequest;
use Home\Request\wechat\AddWechatRequest;
use Home\Request\wechat\FindWechatRequest;
use Home\Request\Weixin\GetSubscribeRequest;
use Home\Request\Weixin\GetWeixinInfoRequest;
use Home\Request\Weixin\GetWeixinRequest;
use Home\Service\ActApplyTimeService;
use Home\Service\ActListService;
use Home\Service\ActService;
use Home\Service\AddNumService;
use Home\Service\AddRecordService;
use Home\Service\CheckApplyService;
use Home\Service\CheckDayNumService;
use Home\Service\FindApplyService;
use Home\Service\FindWechatService;
use Home\Service\GetApplyNumService;
use Home\Service\GetRecordNumService;
use Home\Service\GetSubscribeService;
use Home\Service\GetWeixinIdService;
use Home\Service\GetWeixinInfoService;
use Home\Service\GetWeixinService;
use Weixin\Service\GetCookieService;
use Home\Service\GetEventService;
use Home\Service\SelectApplyService;
use Home\Service\SubmitMsgService;
use Home\Service\UploadService;
use Wechat\Loader;


class IndexController extends HomeController
{
/*
    public function test()
    {
        $image = new \Think\Image();
        $image->open( './Uploads/2017-08-04/59844153d1a99.jpg' );
    }*/

    public function actList()
    {
        //活动显示页面
        $service = new ActListService();
        $response = $service->run();
        if ($response->getItIsNull() == true) {
            $data = array();
        } else {
            $data = $response->getData();
        }
        //dump($data);
        $this->assign('act', $data);
        $this->display();
    }

    public function index()
    {
        $this->display('abc');
    }

    public function index2()
    {
        $weixin = new \Weixin\Controller\IndexController();
        $weixin->oauth();

        $service = new GetCookieService();
        $response = $service->run();
        $openid = $response->getOpenId();
        $user_id = $response->getUserId();

        //dump($user_id);
        /*dump($openid);
        dump($user_id);*/

        $keyword = I('keyword', null);
        $id = I('id', null);
        $order = I('order', null);
        $limit = I('limit', null);
        //echo $limit;
        //echo $order;
        //echo $keyword;

        $request = new GetActRequest();
        $request->setId($id);
        $service = new ActService();
        $response = $service->run($request);
        if ($response->getItIsNull() == true) {
            throw new HomeException(30002);
        } else {
            $data = $response->getData();
        }

        // 获取投票人数
        $service = new GetRecordNumService();
        $response = $service->run();
        if ($response->getItIsNull() == true) {
            throw new HomeException(30017);
        } else {
            $recordNum = $response->getRecordNum();
        }
        // dump($recordNum);


        $request = new SelectApplyRequest();
        $request->setOrder($order);
        $request->setLimit($limit);
        $request->setKeyword($keyword);
        $request->setActId($id);
        $service = new SelectApplyService();
        $response = $service->run($request);
        if ($response->getItIsNull() == true) {
            $apply = '';
        } else {
            $apply = $response->getData();
        }
        //dump($apply);

        //dump($data);
        $count = count($apply);

        include_once APP_PATH . 'Wechat/Loader.php';
        $script = $weixin->load_wechat('Script');
        // 获取JsApi使用签名，通常这里只需要传 $url参数
        $protocol = (!empty($_SERVER[HTTPS]) && $_SERVER[HTTPS] !== off || $_SERVER[SERVER_PORT] == 443) ? "https://" : "http://";
        $url = $protocol . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $options = $script->getJsSign($url);
        // 处理执行结果
        if ($options === FALSE) {
            // 接口失败的处理
            echo $script->errMsg;
        } else {
            // 接口成功的处理
        }

        $this->assign('count', $count);
        $this->assign('act', $data);
        $this->assign('apply', $apply);
        $this->assign('user_id', $user_id);
        $this->assign('openid', $openid);
        $this->assign('options', $options);
        // dump($user_id);
        // dump($openid);
        $this->assign('recordNum', $recordNum);
        $this->display();
    }

    public function player()
    {
        $weixin = new \Weixin\Controller\IndexController();
        $weixin->oauth();

        $service = new GetCookieService();
        $response = $service->run();
        $openid = $response->getOpenId();
        $user_id = $response->getUserId();

        /*dump($openid);
        dump($user_id);*/

        //选手信息详情页
        $id = I('id', null);
        $apply_id = I('apply_id', null);

        $request = new GetActRequest();
        $request->setId($id);
        $service = new ActService();
        $response = $service->run($request);
        if ($response->getItIsNull() == true) {
            $data = array();
        } else {
            $data = $response->getData();
        }
        //dump($data);

        $request = new FindApplyRequest();
        $request->setApplyId($apply_id);
        $service = new FindApplyService();
        $response = $service->run($request);

        if ($response->getItIsNull() == true) {
            $applyOne = '';
        } else {
            $applyOne = $response->getData();
        }

        include_once APP_PATH . 'Wechat/Loader.php';
        $script = $weixin->load_wechat('Script');
        // 获取JsApi使用签名，通常这里只需要传 $url参数
        $protocol = (!empty($_SERVER[HTTPS]) && $_SERVER[HTTPS] !== off || $_SERVER[SERVER_PORT] == 443) ? "https://" : "http://";
        $url = $protocol . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $options = $script->getJsSign($url);
        // 处理执行结果
        if ($options === FALSE) {
            // 接口失败的处理
            echo $script->errMsg;
        } else {
            // 接口成功的处理
        }

        //dump($applyOne);
        $this->assign('applyOne', $applyOne);
        $this->assign('act', $data);
        $this->assign('user_id', $user_id);
        $this->assign('openid', $openid);
        $this->assign('options', $options);
        $this->display();
    }

    public function apply()
    {
        /*$weixin = new \Weixin\Controller\IndexController();
        $weixin->oauth();

        $service = new GetCookieService();
        $response = $service->run();
        $openid = $response->getOpenId();
        $user_id = $response->getUserId();*/

        /*dump($openid);
        dump($user_id);*/

        //报名页面
        $id = I('id', null);

        $request = new GetActRequest();
        $request->setId($id);
        $service = new ActService();
        $response = $service->run($request);
        if ($response->getItIsNull() == true) {
            $data = array();
        } else {
            $data = $response->getData();
        }

        /*include_once APP_PATH . 'Wechat/Loader.php';
        $script = $weixin->load_wechat('Script');
        // 获取JsApi使用签名，通常这里只需要传 $url参数
        $protocol = (!empty($_SERVER[HTTPS]) && $_SERVER[HTTPS] !== off || $_SERVER[SERVER_PORT] == 443) ? "https://" : "http://";
        $url = $protocol . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $options = $script->getJsSign($url);
        // 处理执行结果
        if ($options === FALSE) {
            // 接口失败的处理
            echo $script->errMsg;
        } else {
            // 接口成功的处理
        }*/

        //dump($data);
        $this->assign('act', $data);
      /*  $this->assign('user_id', $user_id);
        $this->assign('openid', $openid);
        $this->assign('options', $options);*/
        $this->display();
    }

    public function line()
    {
        $weixin = new \Weixin\Controller\IndexController();
        $weixin->oauth();

        $service = new GetCookieService();
        $response = $service->run();
        $openid = $response->getOpenId();
        $user_id = $response->getUserId();

        /*dump($openid);
        dump($user_id);*/

        //获取排名信息
        $id = I('id', null);

        $keyword = null;
        $order = 'vote_num';
        $limit = null;

        $request = new GetActRequest();
        $request->setId($id);
        $service = new ActService();
        $response = $service->run($request);
        if ($response->getItIsNull() == true) {
            $data = array();
        } else {
            $data = $response->getData();
        }

        $request = new SelectApplyRequest();
        $request->setOrder($order);
        $request->setLimit($limit);
        $request->setKeyword($keyword);
        $request->setActId($id);
        $service = new SelectApplyService();
        $response = $service->run($request);
        if ($response->getItIsNull() == true) {
            $apply = '';
        } else {
            $apply = $response->getData();
        }

        include_once APP_PATH . 'Wechat/Loader.php';
        $script = $weixin->load_wechat('Script');
        // 获取JsApi使用签名，通常这里只需要传 $url参数
        $protocol = (!empty($_SERVER[HTTPS]) && $_SERVER[HTTPS] !== off || $_SERVER[SERVER_PORT] == 443) ? "https://" : "http://";
        $url = $protocol . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $options = $script->getJsSign($url);
        // 处理执行结果
        if ($options === FALSE) {
            // 接口失败的处理
            echo $script->errMsg;
        } else {
            // 接口成功的处理
        }

        // dump($apply);

        //dump($data);
        $this->assign('apply', $apply);
        $this->assign('act', $data);
        $this->assign('user_id', $user_id);
        $this->assign('openid', $openid);
        $this->assign('options', $options);
        $this->display();
    }

    public function explain()
    {
        $weixin = new \Weixin\Controller\IndexController();
        $weixin->oauth();

        $service = new GetCookieService();
        $response = $service->run();
        $openid = $response->getOpenId();
        $user_id = $response->getUserId();

        /*dump($openid);
        dump($user_id);*/

        //获取活动介绍
        $id = I('id', null);

        $request = new GetActRequest();
        $request->setId($id);
        $service = new ActService();
        $response = $service->run($request);
        if ($response->getItIsNull() == true) {
            $data = array();
        } else {
            $data = $response->getData();
        }

        include_once APP_PATH . 'Wechat/Loader.php';
        $script = $weixin->load_wechat('Script');
        // 获取JsApi使用签名，通常这里只需要传 $url参数
        $protocol = (!empty($_SERVER[HTTPS]) && $_SERVER[HTTPS] !== off || $_SERVER[SERVER_PORT] == 443) ? "https://" : "http://";
        $url = $protocol . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $options = $script->getJsSign($url);
        // 处理执行结果
        if ($options === FALSE) {
            // 接口失败的处理
            echo $script->errMsg;
        } else {
            // 接口成功的处理
        }

        //dump($data);
        $this->assign('act', $data);
        $this->assign('user_id', $user_id);
        $this->assign('openid', $openid);
        $this->assign('options', $options);
        $this->display();
    }

    public function upload_test()
    {
        dump(C('COOKIE_EXPIRE'));

        $this->display();
    }

    public function upload()
    {
        //上传图片
        $service = new UploadService();
        $response = $service->run();
        $data = $response->getData();
        $this->ajaxReturn($data);
    }

    public function test()
    {
        echo 1;
    }

    public function submitMsg()
    {
        $result = array(
            'request' => array(
                'status' => 'success',
                'errcode' => 0,
                'info' => ''
            ),
            'result' => array(
                'status' => 'success',
                'errcode' => 0,
                'info' => ''
            )
        );

        // 获取用户关注公众号状态
        $openid = I('openid', null);
        $request = new GetSubscribeRequest();
        $request->setOpenId($openid);
        $service = new GetSubscribeService();

        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        if ($response->getItIsNull() == true) {
            try {
                throw new HomeException(30015);
            } catch (HomeException $e) {
                $result['result']['status'] = 'fail';
                $result['result']['errcode'] = $e->getCode();
                $result['result']['info'] = $e->getMessage();
                $this->ajaxReturn($result);
            }
        } else {
            $subscribe = $response->getSubscribe();
        }

        //dump($subscribe);

        // 判断用户是否关注公众号
        if ($subscribe == 0) {
            try {
                throw new HomeException(30016);
            } catch (HomeException $e) {
                $result['result']['status'] = 'fail';
                $result['result']['errcode'] = $e->getCode();
                $result['result']['info'] = $e->getMessage();
                $this->ajaxReturn($result);
            }
        }

        $request = new GetWeixinRequest();
        $request->setOpenId($openid);
        $service = new GetWeixinService();
        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        try {
            if ($response->getItIsNull() == true) {
                throw new HomeException(30014);
            } else {
                $nickname = $response->getNickName();
                $headimgurl = $response->getHeadImgUrl();
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
            $this->ajaxReturn($result);
        }

        // 提交报名信息
        $request = new SubmitMsgRequest();
        $name = I('get.name', null);
        $phone = I('get.phone', null);
        $picture_id = I('get.picture_id', null);
        $introduce = I('get.introduce', null);
        $act_id = I('get.act_id', null);
        $user_id = I('get.user_id', null);
        $age = I('get.age', null);
        $address = I('get.address', null);

        $request->setName($name);
        $request->setPhone($phone);
        $request->setPictureId($picture_id);
        $request->setIntroduce($introduce);
        $request->setUserId($user_id);
        $request->setActId($act_id);
        $request->setNickName($nickname);
        $request->setHeadImgUrl($headimgurl);
        $request->setAge($age);
        $request->setAddress($address);

        $service = new SubmitMsgService();

        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        try {
            if ($response->getItIsNull() == true) {
                throw new HomeException(30001);
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
        }
        $this->ajaxReturn($result);
    }

    public function checkApply()
    {
        $result = array(
            'request' => array(
                'status' => 'success',
                'errcode' => 0,
                'info' => ''
            ),
            'result' => array(
                'status' => 'success',
                'errcode' => 0,
                'info' => ''
            )
        );
        //判断报名时间
        $act_id = I('act_id', null);
        $request = new ActApplyTimeRequest();
        $request->setActId($act_id);
        $service = new ActApplyTimeService();
        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        if ($response->getItIsNull() == true) {
            throw new HomeException(30006);
        } else {
            $data = $response->getData();
        }

        //dump(date('Y-m-d H:i:s'));

        $data['apply_start_time'] = strtotime($data['apply_start_time']);
        $data['apply_end_time'] = strtotime($data['apply_end_time']);
        $time = time();
        try {
            if ($time < $data['apply_start_time']) {
                throw new HomeException(30009);
            } else if ($time > $data['apply_end_time']) {
                throw new HomeException(30010);
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
            $this->ajaxReturn($result);
        }


        //判断是否报名过
        $user_id = I('get.user_id', null);
        $request = new CheckApplyRequest();
        $request->setUserId($user_id);
        $service = new CheckApplyService();
        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }
        if ($response->getItIsNull() == true) {
            $result['result']['data'] = '';
        } else {
            $result['result']['data'] = $response->getData();
        }
        $this->ajaxReturn($result);
    }

    public function addRecord()
    {
        $result = array(
            'request' => array(
                'status' => 'success',
                'errcode' => 0,
                'info' => ''
            ),
            'result' => array(
                'status' => 'success',
                'errcode' => 0,
                'info' => ''
            )
        );

        // 获取用户关注公众号状态
        $openid = I('openid', null);
        $request = new GetSubscribeRequest();
        $request->setOpenId($openid);
        $service = new GetSubscribeService();

        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        if ($response->getItIsNull() == true) {
            try {
                throw new HomeException(30015);
            } catch (HomeException $e) {
                $result['result']['status'] = 'fail';
                $result['result']['errcode'] = $e->getCode();
                $result['result']['info'] = $e->getMessage();
                $this->ajaxReturn($result);
            }
        } else {
            $subscribe = $response->getSubscribe();
        }

        //dump($subscribe);

        // 判断用户是否关注公众号
        if ($subscribe == 0) {
            try {
                throw new HomeException(30016);
            } catch (HomeException $e) {
                $result['result']['status'] = 'fail';
                $result['result']['errcode'] = $e->getCode();
                $result['result']['info'] = $e->getMessage();
                $this->ajaxReturn($result);
            }
        }


        // 判断投票时间
        $act_id = I('act_id', null);
        $request = new ActApplyTimeRequest();
        $request->setActId($act_id);
        $service = new ActApplyTimeService();
        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        if ($response->getItIsNull() == true) {
            throw new HomeException(30006);
        } else {
            $data = $response->getData();
        }

        //dump(date('Y-m-d H:i:s'));

        $data['act_start_time'] = strtotime($data['act_start_time']);
        $data['act_end_time'] = strtotime($data['act_end_time']);
        $time = time();
        try {
            if ($time < $data['act_start_time']) {
                throw new HomeException(30007);
            } else if ($time > $data['act_end_time']) {
                throw new HomeException(30008);
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
            $this->ajaxReturn($result);
        }

        $apply_id = I('apply_id', null);
        $user_id = I('user_id', null);
        $time = date('Y-m-d H:i:s');


        //判断用户今日最大投票数是否超过限制
        $request = new CheckDayNumRequest();
        $request->setUserId($user_id);
        $request->setActId($act_id);
        $service = new CheckDayNumService();
        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        try {
            if ($response->getItIsNull() == true) {
                throw new HomeException(30011);
            } else {
                $data = $response->getData();
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
            $this->ajaxReturn($result);
        }
        $flag = $response->getFlag();

        // 通过openid获取用户nickname、headimgurl
        $request = new GetWeixinRequest();
        $request->setOpenId($openid);
        $service = new GetWeixinService();
        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        try {
            if ($response->getItIsNull() == true) {
                throw new HomeException(30014);
            } else {
                $nickname = $response->getNickName();
                $headimgurl = $response->getHeadImgUrl();
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
            $this->ajaxReturn($result);
        }

        // 通过user_id获取weixin_id
        /*$request = new GetWeixinIdRequest();
        $request->setUserId($user_id);
        $service = new GetWeixinIdService();
        $response = $service->run($request);
        try {
            if ($response->getItIsNull() == true) {
                throw new HomeException(30013);
            } else {
                $weixin_id = $response->getWeixinId();
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
            $this->ajaxReturn($result);
        }*/
        // dump($weixin_id);

        //添加报名人投票数、更新用户最后投票时间、增加用户今日投票数、用户nickname、头像headimgurl
        $request = new AddNumRequest();
        $request->setApplyId($apply_id);
        $request->setUserId($user_id);
        $request->setFlag($flag);

        $service = new AddNumService();
        $response = $service->run($request);
        try {
            if ($response->getItIsNull() == true) {
                throw new HomeException(30005);
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getMessage();
            $result['result']['info'] = $e->getCode();
            $this->ajaxReturn($result);
        }


        // 通过weixin_id获取用户nickname、headimgurl
        /*$request = new GetWeixinInfoRequest();
        $request->setWeixinId($weixin_id);
        $service = new GetWeixinInfoService();
        $response = $service->run($request);
        try {
            if ($response->getItIsNull() == true) {
                throw new HomeException(30014);
            } else {
                $nickname = $response->getNickName();
                $headimgurl = $response->getHeadImgUrl();
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
        }*/

        /*dump($nickname);
        dump($headimgurl);*/

        //添加投票记录
        $request = new AddRecordRequest();
        $request->setActId($act_id);
        $request->setApplyId($apply_id);
        $request->setUserId($user_id);
        $request->setTime($time);
        $request->setNickName($nickname);
        $request->setHeadImgUrl($headimgurl);

        $service = new AddRecordService();
        try {
            $response = $service->run($request);
        } catch (HomeException $e) {
            $result['request']['status'] = 'fail';
            $result['request']['errcode'] = $e->getCode();
            $result['request']['info'] = $e->getMessage();
            unset($result['result']);
            $this->ajaxReturn($result);
        }

        try {
            if ($response->getItIsNull() == true) {
                throw new HomeException(30003);
            }
        } catch (HomeException $e) {
            $result['result']['status'] = 'fail';
            $result['result']['errcode'] = $e->getCode();
            $result['result']['info'] = $e->getMessage();
            $this->ajaxReturn($result);
        }
        $this->ajaxReturn($result);
    }
}